<?php

require_once 'Zend/Validate/Abstract.php';

/**
 * @category   Zend
 * @package    Zend_Validate
 * @copyright  Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class App_Validate_Unique extends Zend_Validate_Abstract {

   const INVALID      = 'invalid';
   const NOT_UNIQUE    = 'notUnique';
   const STRING_EMPTY = 'stringEmpty';

   public $table;
   public $field;
   
   protected static $_filter = null;

   protected $_messageTemplates = array(
      self::INVALID      => "Invalid type given, value should be a string",
      self::NOT_UNIQUE    => "'%value%' is not unique",
      self::STRING_EMPTY => "'%value%' is an empty string"
   );

   
   public function __construct($table, $field) {
      $this->table = $table;
      $this->field = $field;
   }

   public function isValid($value) {
      
      if (!is_string($value)) {
         $this->_error(self::INVALID);
         return false;
      }

      $this->_setValue($value);

      if ('' === $value) {
         $this->_error(self::STRING_EMPTY);
         return false;
      }

      $db = Zend_Registry::get('db');
      $select = $db->select()
                   ->from($this->table, $this->field)
                   ->where($this->field . '= ?', $value);
      $stmt = $db->query($select);
      $res = $stmt->fetchAll();

      if($res) {
         $this->_error(self::NOT_UNIQUE);
         return false;
      }
      return true;
   }

}
